﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Text;
namespace Fcom.VNInsurance.Web.Controllers
{
    public class AccountController : Fcom.VNInsurance.Web.CultureHelper.CultureController
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetRegisterCaptcha()
        {
            //Captcha Image Size  Width - Height
            int width = 125;
            int height = 25;

            //Captcha String
            dynamic fontFamily = "Tahoma";
            // -  Generate Random
            int randomsize = 5;
            StringBuilder randomstringbuilder = new StringBuilder();
            Random random = new Random(DateTime.Now.Millisecond);
            char ch = '\0';
            for (int i = 0; i <= randomsize - 1; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                randomstringbuilder.Append(ch);
            }
            dynamic captchaString = randomstringbuilder.ToString();

            // Create a new 32-bit bitmap image.
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);

            // Fill in the background.
            System.Drawing.Drawing2D.HatchBrush hatchBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Wave, System.Drawing.Color.LightGray, System.Drawing.Color.White);
            g.FillRectangle(hatchBrush, rect);

            // Set up the text font.
            System.Drawing.SizeF size = default(System.Drawing.SizeF);
            float fontSize = rect.Height + 1;
            System.Drawing.Font font = null;
            System.Drawing.StringFormat format = new System.Drawing.StringFormat();
            format.Alignment = System.Drawing.StringAlignment.Center;
            format.LineAlignment = System.Drawing.StringAlignment.Center;

            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize -= 1;
                font = new System.Drawing.Font(fontFamily, fontSize, System.Drawing.FontStyle.Bold);
                size = g.MeasureString(captchaString, font, new System.Drawing.SizeF(width, height), format);
            } while (size.Width > rect.Width);

            // Create a path using the text and warp it randomly.
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddString(captchaString, font.FontFamily, Convert.ToInt32(font.Style), font.Size, rect, format);
            float v = 4f;
            System.Drawing.PointF[] points = {
		new System.Drawing.PointF(random.Next(rect.Width) / v, random.Next(rect.Height) / v),
		new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v, random.Next(rect.Height) / v),
		new System.Drawing.PointF(random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v),
		new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v)
	};
            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.Translate(0f, 0f);
            path.Warp(points, rect, matrix, System.Drawing.Drawing2D.WarpMode.Perspective, 0f);

            // Draw the text.
            hatchBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.DashedUpwardDiagonal, System.Drawing.Color.DarkGray, System.Drawing.Color.Black);
            g.FillPath(hatchBrush, path);

            // Add some random noise.
            int m = Math.Max(rect.Width, rect.Height);
            for (int i = 0; i <= Convert.ToInt32(Math.Truncate(rect.Width * rect.Height / 30f)) - 1; i++)
            {
                int x = random.Next(rect.Width);
                int y = random.Next(rect.Height);
                int w = random.Next(m / 50);
                int h = random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }

            // Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

            FileContentResult captchaImageResult = null;
            using (System.IO.MemoryStream mystream = new System.IO.MemoryStream())
            {

                bitmap.Save(mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
                captchaImageResult = base.File(mystream.GetBuffer(), "image/jpeg");

            }
            bitmap.Dispose();

            //Save the Captcha Hash in the Session
            Session["GetRegisterCaptcha"] = captchaString;

            //Return the Captcha Image
            return captchaImageResult;

        }
        [HttpPost]
        public ActionResult CheckEmailExists(string youremail)
        {
            Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
            return Json(new { success = client.checkemailexists(youremail) });
        }
        [HttpPost]
        public ActionResult Register(Models.RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                FcomAccount.Account acc = new FcomAccount.Account();
                acc.GroupID = 1;
                acc.FullName = model.FullName;
                acc.Phone = model.Phone;
                acc.Status = 0;
                acc.Password = model.Password;
                acc.Username = model.Username;
                acc.CreateDate = DateTime.Now;
                acc.Email = model.Username;
                FcomAccount.FcomAccountDataContext db = new FcomAccount.FcomAccountDataContext();
                db.Accounts.InsertOnSubmit(acc);
                db.SubmitChanges();
                FcomAccount.PersionalAccount per = new FcomAccount.PersionalAccount();
                per.Address = model.Address;
                per.Phone = model.Phone;
                per.Firstname = acc.FullName;
                per.Lastname = "";
                per.Username = acc.Username;
                db.PersionalAccounts.InsertOnSubmit(per);
                db.SubmitChanges();
                FormsAuthentication.SetAuthCookie(model.Username, true);
                return RedirectToAction("Index","Home");
            }
            return View();
        }
        public ActionResult Register()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        public ActionResult LogOn()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(Fcom.VNInsurance.Web.Models.LogOnModel model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Username, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Username, true);
                    if (Url.IsLocalUrl(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                

            }
            return View();
        }
        public ActionResult LogOut(string ReturnUrl)
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            if (Url.IsLocalUrl(ReturnUrl))
            {
                return Redirect(ReturnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

        }
        [HttpPost]
        public ActionResult ajSetLogin(string token)
        {
            string sso = DecodeFrom64(token);
            string[] ssa = sso.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            string username = ssa[0];
            FormsAuthentication.SetAuthCookie(username, true);
            Session["tokenme"] = token;
            return Json(new { success = true });
        }
        private string DecodeFrom64(string encodedData)
        {

            byte[] encodedDataAsBytes

                = System.Convert.FromBase64String(encodedData);

            string returnValue =

               System.Text.Encoding.Unicode.GetString(encodedDataAsBytes);

            return returnValue;

        }
        private string EncodeTo64(string toEncode)
        {

            byte[] toEncodeAsBytes

                  = System.Text.Encoding.Unicode.GetBytes(toEncode);

            string returnValue

                  = System.Convert.ToBase64String(toEncodeAsBytes);

            return returnValue;

        }
    }
}
